package com.weixing.mall.base.enums;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.POJONode;
import org.springframework.beans.BeanUtils;

import java.io.IOException;

/**
 * IEnum枚举的自定义反序列化············
 *
 */
public class BaseEnumDeserializer extends JsonDeserializer<IBaseEnum> {
 
    @Override
    @SuppressWarnings("unchecked")
    public IBaseEnum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        System.out.println(jp.getCurrentToken());

        JsonNode node = jp.getCodec().readTree(jp);
        String currentName = jp.currentName();
        Object currentValue = jp.getCurrentValue();
        @SuppressWarnings("rawtypes")
        Class findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        JsonFormat annotation = (JsonFormat) findPropertyType.getAnnotation(JsonFormat.class);
        IBaseEnum valueOf;
        if(annotation == null || annotation.shape() != JsonFormat.Shape.OBJECT) {
            if (node instanceof POJONode) {
                valueOf = (IBaseEnum) getIEnum(findPropertyType, node.get("value").asText());
            }else {
                // Payload传递参数,反序列化
                valueOf = (IBaseEnum) getIEnum(findPropertyType, node.asText());
            }
        }else {
            if (node instanceof POJONode) {
                valueOf = (IBaseEnum) getIEnum(findPropertyType, node.get("value").asText());
            }else {
                // Payload传递参数,反序列化
                valueOf = (IBaseEnum) getIEnum(findPropertyType, node.asText());
            }
        }
        return  valueOf;
    }

    public static <T extends IBaseEnum> Object getIEnum(Class<T> targerType, String source) {
        for (T enumObj : targerType.getEnumConstants()) {
            if (source.equals(String.valueOf(enumObj.getValue()))) {
                return enumObj;
            }
        }
        return null;
    }
 
 
}